package com.alongthink.javademo.queue;
import lombok.extern.slf4j.Slf4j;

import java.util.List;
import java.util.concurrent.*;

@Slf4j
public class BlockingQueueHelper {
    private static final Integer maxQueueSize = 200;//队列大小
    private static BlockingQueue blockingQueue = new LinkedBlockingQueue(maxQueueSize);
    private static ExecutorService threadPool = Executors.newSingleThreadExecutor();
    private static List<byte[]> nowObj = null;


    public static BlockingQueue getBlockingQueue() {
        if (blockingQueue == null) {
            blockingQueue = new LinkedBlockingQueue(maxQueueSize);
        }
        return blockingQueue;
    }

    public static List<byte[]> getNowObj() {
        return nowObj;
    }

    public static void setNowObj(List<byte[]> nowObj) {
        BlockingQueueHelper.nowObj = nowObj;
    }

    public static void clean(){
        if (blockingQueue != null) {
            blockingQueue = null;
        }
    }

    /**
     * 入队操作
     * @param o 队列处理对象（包含request,response,data）
     */
    public static void requestQueue(Object o) {
        if(blockingQueue==null){
            blockingQueue = getBlockingQueue();
        }
        //检测当前的队列大小
        if (blockingQueue.size() < maxQueueSize) {
            //可以正常进入队列
            if (blockingQueue.offer(o)) {
                //添加成功，检测数据处理线程是否正常
                if (!LockFlag.getCustomerRunningFlag()) {
                    //说明处理线程类停止，此时，应重新启动线程进行数据处理
                    LockFlag.setCustomerRunningFlag(true);
                    //example:run
                    CustomerFSY customer = new CustomerFSY(blockingQueue);
                    threadPool.execute(customer);
                }
            } else {
                //进入队列失败，做出相应的处理，或者尝试重新进入队列
                blockingQueue.offer(o);
            }
        } else {
            //队列不正常，或队列大小已达上限，做出相应处理
            try {
                log.info("当前队列大小已超出"+maxQueueSize+"将进行软件移除处理");
                blockingQueue.poll(10, TimeUnit.MILLISECONDS);

                if (blockingQueue.offer(o)) {
                    //添加成功，检测数据处理线程是否正常
                    if (!LockFlag.getCustomerRunningFlag()) {
                        //说明处理线程类停止，此时，应重新启动线程进行数据处理
                        LockFlag.setCustomerRunningFlag(true);
                        //example:run
                        CustomerFSY customer = new CustomerFSY(blockingQueue);
                        threadPool.execute(customer);
                    }
                } else {
                    //进入队列失败，做出相应的处理，或者尝试重新进入队列
                    blockingQueue.offer(o);
                }
            }catch (Exception ex){

            }
        }

    }
}
